# coding:utf-8
import serial,random,time

def hexShow(argv):
    result = ''
    hLen = len(argv)
    for i in xrange(hLen):
        hvol = ord(argv[i])  #ord()的参数是一个ascii字符，返回值是十进制整数
        hhex = '%02x' % hvol #十进制 -> 16进制 ，单引号转化为字面量字符串
        result += hhex + ' ' # 字符串 加法
    print 'hexShow:', result

def hex_checksum(data):   #计算校验和，返回字符创
    checksum = 0x00
    for i in range(0, len(data)):
        x = int(data[i], 16)
        checksum += x
        if checksum > 256:
            checksum = checksum % 256
    return ('%02x' % checksum).upper()
#设置并读取表号
IDsetFirst = 'FE FE FE FE FE 68 AB 57 58 AA AA AA AA AA F2 77 88 99 55 15 00 0A A0 18 03 00 00'
meterID = ['00 00 00 00 00','FF FF FF FF FF', '00 00 00 00 01', '10 10 10 10 10', '55 55 55 55 55','01 23 45 67 89','AB CD EF 99 88']
t = serial.Serial(port='com4', baudrate=9600, timeout=5)
print t.portstr
for i in range(len(meterID)):
    checksumData = IDsetFirst.split() + meterID[i].split()
    meterIDsend = ''.join(checksumData + hex_checksum(checksumData[5:]).split() + ['16'])
    meterIDsend = meterIDsend.decode('hex')
    t.write(meterIDsend)
    time.sleep(4)
    meterIDread = (
    ''.join(('FE FE FE FE FE 68 AB 57 58 AA AA AA AA AA F2 77 88 99 55 03 00 03 81 0A 01 85 16').split())).decode('hex')
    t.write(meterIDread)
    meterIDreceive = t.read(35).encode('hex')
    print '设置的表号是'+''.join(meterID[i].split())
    print meterIDreceive
    print '接收的表号是'+meterIDreceive[28:38].upper()
    if meterIDreceive[28:38].upper() == ''.join(meterID[i].split()):
        print '表号 %d 设置并读取正确'%i
    else:
        print '表号 %d 设置并读取错误'%i
    print'-----------------------------------------------------------------'
    time.sleep(3)

#清除事件记录
clearEventFirst='FE FE FE FE FE 68 AB 57 58'
clearEventMid='F2 77 88 99 55 01 00 03 92 00 01'
clearEventData= clearEventFirst.split() + meterID[i].split()+clearEventMid.split()
clearEventSend = ''.join(clearEventData + hex_checksum(clearEventData[5:]).split() + ['16'])
# print clearEventSend
clearEventSend=clearEventSend.decode('hex')
# print clearEventData
t.write(clearEventSend)
# print '清事件记录'
clearEventReceive = t.read(40).encode('hex')
print '清除事件记录'+'\n'+'接收'+clearEventReceive.upper()
receiveData = clearEventData[0:19] +['81','00','05']+clearEventData[-3:]+ hex_checksum(clearEventData[5:]).split() + ['16']
# print receiveData
print '比对'+''.join(receiveData+hex_checksum(receiveData[5:]).split()+['16','FE'])
if  clearEventReceive.upper()[:58] ==(''.join(receiveData+hex_checksum(receiveData[5:]).split()+['16','FE']))[:58]:
    print '清除事件记录成功'
else:
    print '失败'
time.sleep(3)